package oriol.forns.gutierrez;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class PantallasBack extends SurfaceView{
	private PantallasThread bgdt;
	private SurfaceHolder holder;
	private Paint fons;
	private Shader shader;
	private Nuvols nuvol;
	private BitmapFactory.Options options;
	
	private boolean surfacecreated;
	private boolean threadrunning;
	
	
	public PantallasBack(Context context) {
		super(context);
		init();
	}
	
	public PantallasBack(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public PantallasBack(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init() {
		surfacecreated = false;
		threadrunning = false;
		holder = getHolder();
		holder.addCallback(new Callback() {
			
			public void surfaceDestroyed(SurfaceHolder holder) {
				stopthread();
				surfacecreated = false;
			}
			
			public void surfaceCreated(SurfaceHolder holder) {
				holder.setFormat(PixelFormat.RGBA_8888);
				
				fons = new Paint();
				
				
				shader = new RadialGradient(0, 0, getHeight()/2, 0xFFFFFFFF, 0xFFA4D8FF, Shader.TileMode.CLAMP);
				fons.setShader(shader);
				nuvol = GV.Instancies.nuvols;
				
				surfacecreated = true;
			}
			
			public void surfaceChanged(SurfaceHolder holder, int format, int width,	int height) {
				startthread();
			}
		});
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawRect(0, 0, getWidth(), getHeight(), fons);
		nuvol.actualitza();
		nuvol.draw(canvas);
		GV.Instancies.nuvols = nuvol;
	}
	
	public void startthread(){
		if(!surfacecreated) return;
		if(threadrunning) return;
		bgdt = new PantallasThread(this);
		bgdt.setRunning(true);
		bgdt.start();
		threadrunning = true;
	}
	
	public void stopthread() {
		if(!surfacecreated) return;
		if(!threadrunning) return;
		boolean retry = true;
		while (retry) {
			try {
				bgdt.setRunning(false);
				bgdt.join();
				threadrunning = false;
				retry = false;
				
			} catch (InterruptedException e) {}
		}
	}
}
